package cn.bandeqing.config.service.impl;

import cn.bandeqing.base.resp.Resp;
import cn.bandeqing.frame.exception.CodeException;
import cn.bandeqing.sys.resp.ConfigResp;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import cn.bandeqing.config.entity.Config;
import cn.bandeqing.config.mapper.ConfigMapper;
import cn.bandeqing.config.service.IConfigService;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.springframework.stereotype.Service;

import static cn.bandeqing.config.entity.table.ConfigTableDef.CONFIG;

/**
 * 配置 服务层实现。
 *
 * @author fugui
 * @since 2024-01-05
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {

    @Override
    public Integer keyInt(String key, int defaultVal) {
        Integer val = getOneAs(QueryWrapper.create()
                .select(CONFIG.CONFIG_VAL_INT)
                .where(CONFIG.CONFIG_KEY.eq(key)), Integer.class);
        if (ObjUtil.isNull(val)) {
            val = defaultVal;
            Assert.isTrue(save(Config.builder()
                    .configKey(key)
                    .configValInt(defaultVal)
                    .build()), () -> new CodeException(""));
        }
        return val;
    }

    @Override
    public String keyStr(String key, String defaultVal) {
        String val = getOneAs(QueryWrapper.create()
                .select(CONFIG.CONFIG_VAL_STR)
                .where(CONFIG.CONFIG_KEY.eq(key)), String.class);
        if (StrUtil.isBlank(val)) {
            val = defaultVal;
            Assert.isTrue(save(Config.builder()
                    .configKey(key)
                    .configValStr(defaultVal)
                    .build()), CodeException::new);
        }
        return val;
    }

}
